import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import {
  cumulate,
  arrange,
  summary,
  policyCompute,
  stepCut,
} from "@/views/FlowStatus/utils";

import policyCompute45 from "@/views/FlowStatus/utils/PolicyCompute_v4.5.js";

import fetchSummaryData from "./fetchSummaryData.js";
import fetchHourlyData from "./fetchHourlyData.js";

const arrangeKeys = ["airport", "type", "point"];
const timeFormat = "YYYY-MM-DD HH:mm:ss";
const icaoCodes = ["ZUUU", "ZUTF", "ZUMY", "ZUYB", "ZULZ"];

export default function ({ replyTMA, replyAP, useAP, dataInterval, dataStep }) {
  // console.log("fetchData", {
  //   replyTMA,
  //   replyAP,
  //   useAP,
  //   dataInterval,
  //   dataStep,
  // });

  // 如果未输入关键数据，退出
  if (!replyTMA || !replyAP) {
    ElMessage.warning("出错了，未能检索到数据(⊙o⊙)…");
    return null;
  }

  // 配置默认值
  if (!useAP) {
    useAP = false;
  }
  if (!dataInterval) {
    dataInterval = 4;
  }
  if (!dataStep) {
    dataStep = 4;
  }

  // 配置数据
  const version = replyTMA.version;
  const rawSector = replyTMA.sector;
  const rawDetails = replyTMA.details;
  const begTime = replyTMA.begTime;

  const tagsTerminal = replyTMA.tags;
  const rawTerminalData = replyTMA.rawData;
  const rawTerminalPlanData = replyTMA.rawDataOld;

  const tagsAirport = replyAP.tags;
  const rawAirportData = replyAP.content;
  const rawAirportPlanData = replyAP.history;

  if (!rawTerminalData.length || !rawAirportData.length) {
    ElMessage.warning("出错了，未能检索到数据(⊙o⊙)…");
    return null;
  }

  // 生成实际数据

  // {"direction":{"ZUUU":"N","ZUTF":"N"},"runwayCodes":{"ZUUU":"N12","ZUTF":"N321"},"runwayUtilize":{"zuuu":{"direction":"N","code":"N12","detail":{"W":"1","E":"2","02L":["D"],"02R":["A"],"20R":[],"20L":[]}},"zutf":{"direction":"N","code":"N321","runway":{"W":"3","E":"2","N":"1","01":[],"02":[],"19":[],"20":[],"11":["D"]}}},"sectorCount":9,"activity":["新津","遂宁","广汉","绵阳","巴中","广元"],"seats":{"CN02":["CKGH","CKGL","LZ01","LZ02","LZ03","LZ04"],"TM01":["AP01","AP11","AP18","AP1A"],"TM02":["AP02","AP03"],"TM04":["AP04","AP9L","AP9R"],"TM06":["AP06","AP14","AP5H","AP5L"],"TM07":["AP7L","AP7R"],"TM08":["AP81","APA1"],"TM12":["AP12","APL7","APL9","APR7","APR9"],"TM13":["AP13"]},"users":{"CN02":["李琦欣","黄世豪","吴昊"],"TM01":["张家宁","方舒杨","王森"],"TM02":["姜信哲","苟翔","蒋毅"],"TM04":["罗静心","高蕴渌","李古"],"TM06":["李培恒","廖伟2","张燚"],"TM07":["王俊昕","张博楠"],"TM08":["靳荆","谢言艺","魏天宇"],"TM12":["王振强","周游"],"TM13":["张孟冉","李剑","殷柯阳"]},"supervisors":{"OMA01":["李竞博"],"SUP01":["黄建明"],"SUP02":["王涛2"]},"ExtraSeats":["OMA01","SUP01","SUP02"],"isIPIA":0}

  const realSectorList = stepCut(rawSector, dataInterval, dataStep, "avgRound");

  const rawSeatList = rawDetails.map((cell) => {
    let count = 0;
    if (cell && cell.users) {
      Object.keys(cell.users).forEach((code) => {
        if (cell.users[code].length >= 2) {
          count += 2;
        } else if (cell.users[code].length > 0) {
          count += 1;
        }
      });
    }
    // 独立进近席位数+1 (NTZ)
    if (cell && cell.isIPIA && (cell.isIPIA == 1 || cell.isIPIA == true)) {
      count += 1;
    }
    // users
    return count;
  });
  const realSeatList = stepCut(rawSeatList, dataInterval, dataStep, "max");

  const rawIpia = rawDetails.map((cell) => {
    if (cell && cell.isIPIA && (cell.isIPIA == 1 || cell.isIPIA == true)) {
      return 1;
    } else {
      return 0;
    }
  });
  const realIpiaList = stepCut(rawIpia, dataInterval, dataStep, "avgRound");

  realIpiaList.forEach((val, i) => {
    if (realSectorList[i]) {
      realSectorList[i] += val;
    }
  });

  const rawSupList = rawDetails.map((cell) => {
    if (cell && cell.supervisors) {
      return Math.max(1, Object.keys(cell.supervisors).length);
    } else {
      return 1;
    }
  });
  // console.log("rawSupList", rawSupList);
  const realSupList = stepCut(rawSupList, dataInterval, dataStep, "avgRound");

  const { directionZUUU, directionZUTF } = fetchDirection(rawDetails);
  const realDirectionList = {
    ZUUU: stepCut(directionZUUU, dataInterval, dataStep, "more"),
    ZUTF: stepCut(directionZUTF, dataInterval, dataStep, "more"),
  };

  // console.log("fetchData", { directionZUUU, directionZUTF, realDirectionList });

  const isAfter = dayjs().isAfter(dayjs(begTime).add(24, "hour"));

  // 如果未输入关键数据，退出
  if (
    !rawTerminalData ||
    rawTerminalData.length == 0 ||
    !rawAirportData ||
    rawAirportData.length == 0
  ) {
    ElMessage.warning("出错了，未能检索到数据(⊙o⊙)…");
    return null;
  }

  // 如果使用机场架次代替终端区架次，则机场数据不进行过滤
  const airportKeys = useAP
    ? ["ZUUU", "ZUTF", "ZUMY", "ZUYB", "ZULZ", "DEP", "ARR"]
    : ["ZUYB", "ZULZ", "DEP", "ARR"];

  const terminalKeys = ["ZUUU", "ZUTF", "ZUMY", "DEP", "ARR"];

  // 根据 dataInterval 和 dataStep 进行数据累加
  // 累加终端区架次
  // 如果使用机场架次代替终端区架次，不处理终端区数据

  const cumulatedTerminalData = useAP
    ? null
    : cumulate(rawTerminalData, dataInterval, dataStep);
  const cumulatedTerminalPlanData = useAP
    ? null
    : cumulate(rawTerminalPlanData, dataInterval, dataStep);

  // 累加机场架次

  const cumulatedAirportData = cumulate(rawAirportData, dataInterval, dataStep);
  const cumulatedAirportPlanData = cumulate(
    rawAirportPlanData,
    dataInterval,
    dataStep
  );

  // console.log("fetchData", {
  //   cumulatedTerminalData,
  //   cumulatedTerminalPlanData,
  //   cumulatedAirportData,
  //   cumulatedAirportPlanData,
  // });

  // 生成 Arranged 端区架次
  // 如果使用机场架次代替终端区架次，不处理终端区数据

  const arrangedTerminalData = useAP
    ? null
    : arrange(
        cumulatedTerminalData,
        tagsTerminal,
        begTime,
        dataInterval,
        arrangeKeys,
        timeFormat
      );

  const arrangedTerminalPlanData = useAP
    ? null
    : arrange(
        cumulatedTerminalPlanData,
        tagsTerminal,
        begTime,
        dataInterval,
        arrangeKeys,
        timeFormat
      );

  // 生成 Arranged 机场架次

  const arrangedAirportData = arrange(
    cumulatedAirportData,
    tagsAirport,
    begTime,
    dataInterval,
    arrangeKeys,
    timeFormat
  );

  const arrangedAirportPlanData = arrange(
    cumulatedAirportPlanData,
    tagsAirport,
    begTime,
    dataInterval,
    arrangeKeys,
    timeFormat
  );

  // console.log("fetchData", {
  //   arrangedTerminalData,
  //   arrangedTerminalPlanData,
  //   arrangedAirportData,
  //   arrangedAirportPlanData,
  // });

  // 统计终端区架次
  // 如果使用机场架次代替终端区架次，不处理终端区数据

  const summaryTerminalData = useAP
    ? null
    : summary(cumulatedTerminalData, tagsTerminal, terminalKeys);

  const summaryTerminalPlanData = useAP
    ? null
    : summary(cumulatedTerminalPlanData, tagsTerminal, terminalKeys);

  // 统计机场区架次

  const summaryAirportData = summary(
    cumulatedAirportData,
    tagsAirport,
    airportKeys
  );

  const summaryAirportPlanData = summary(
    cumulatedAirportPlanData,
    tagsAirport,
    airportKeys
  );

  // 合并 summary 数据

  const summaryData = useAP
    ? summaryAirportData
    : {
        airport: {
          ...summaryTerminalData.airport,
          ...summaryAirportData.airport,
        },
      };

  const summaryPlanData = useAP
    ? summaryAirportData
    : {
        airport: {
          ...summaryTerminalPlanData.airport,
          ...summaryAirportPlanData.airport,
        },
      };

  // 合并 Arranged 数据
  // 在 arrangedData 中注入 real 数据

  const arrangedData = injectData(
    policyCompute45(
      useAP
        ? arrangedAirportData
        : arrangedTerminalData.map((dataTMA, i, arr) => {
            const dataAP = arrangedAirportData[i];
            const dataMerge = {
              moment: dataTMA.moment,
              timestamp: dataTMA.timestamp,
              airport: {},
              total: 0,
            };
            Object.keys(dataTMA.airport).forEach((icao) => {
              if (!airportKeys.includes(icao)) {
                dataMerge.airport[icao] = dataTMA.airport[icao];
                dataMerge.total += dataTMA.airport[icao].total;
              }
            });
            Object.keys(dataAP.airport).forEach((icao) => {
              if (airportKeys.includes(icao)) {
                dataMerge.airport[icao] = dataAP.airport[icao];
                dataMerge.total += dataAP.airport[icao].total;
              }
            });
            // dataMerge.total = dataTMA.total + dataAP.total;
            return dataMerge;
          })
    ),
    {
      sector: realSectorList,
      dirUU: realDirectionList.ZUUU,
      dirTF: realDirectionList.ZUTF,
      ipia: realIpiaList,
      super: realSupList,
      seats: realSeatList,
    },
    "real"
  );

  const arrangedPlanData = policyCompute45(
    useAP
      ? arrangedAirportPlanData
      : arrangedTerminalPlanData.map((dataTMA, i, arr) => {
          const dataAP = arrangedAirportPlanData[i];
          const dataMerge = {
            moment: dataTMA.moment,
            timestamp: dataTMA.timestamp,
            airport: {},
            total: 0,
          };
          Object.keys(dataTMA.airport).forEach((icao) => {
            if (!airportKeys.includes(icao)) {
              dataMerge.airport[icao] = dataTMA.airport[icao];
              dataMerge.total += dataTMA.airport[icao].total;
            }
          });
          Object.keys(dataAP.airport).forEach((icao) => {
            if (airportKeys.includes(icao)) {
              dataMerge.airport[icao] = dataAP.airport[icao];
              dataMerge.total += dataAP.airport[icao].total;
            }
          });
          // dataMerge.total = dataTMA.total + dataAP.total;
          return dataMerge;
        })
  );

  // console.log("arrangedData.length", arrangedData.length);
  // console.log("arrangedPlanData.length", arrangedPlanData.length);

  // 注入实际扇区以及独立进近信息

  arrangedData.forEach((cell, i, arr) => {});

  const tableHourlyData = fetchHourlyData({
    arrangedData,
    arrangedPlanData,
    icaoCodes,
  });

  const tableSummaryData = fetchSummaryData({
    summaryData,
    summaryPlanData,
    icaoCodes,
    isAfter,
  });

  const output = {
    version,
    targetDate: begTime,
    // summary: {
    //   tmaReal: summaryTerminalData,
    //   tmaPlan: summaryTerminalPlanData,
    //   apReal: summaryAirportData,
    //   apPlan: summaryAirportPlanData,
    // },
    arranged: {
      mixReal: arrangedData,
      mixPlan: arrangedPlanData,
    },
    // table: { summary: tableSummaryData, hourly: tableHourlyData },
    useAP,
    summary: tableSummaryData,
    hourly: tableHourlyData,
  };

  console.log("fetchData", output);

  return output;
}

const fetchDirection = (details) => {
  const directionZUUU = new Array(details.length).fill("");
  const directionZUTF = new Array(details.length).fill("");
  details.forEach((cell, i, arr) => {
    if (cell && cell.direction) {
      if (cell.direction.ZUUU) {
        directionZUUU[i] = cell.direction.ZUUU;
      }
      if (cell.direction.ZUTF) {
        directionZUTF[i] = cell.direction.ZUTF;
      }
    }
  });
  return { directionZUUU, directionZUTF };
};

const injectData = (origin, records, subKey = null) => {
  if (!records || !origin) {
    console.error("injectData error: Invalid origin or records!");
    return null;
  }
  // if (origin.length != records.length) {
  //   console.error("injectData error: Unequal length of origin and records!");
  //   return null;
  // }
  const inRoot = !subKey || typeof subKey != "string";
  for (let i = 0; i < origin.length; i++) {
    const injectData = {};
    Object.keys(records).forEach((key) => {
      const rec = records[key];
      if (origin.length != rec.length) {
        console.error(
          `injectData error: Unequal length of origin and records(${key})!`
        );
      } else {
        if (inRoot) {
          origin[i][key] = rec[i];
        } else {
          injectData[key] = rec[i];
        }
      }
    });
    if (!inRoot) {
      origin[i][subKey] = injectData;
    }
  }
  return origin;
};
